package handler

import (
	"car-trade-mgr/cache"
	"car-trade-mgr/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarMgrList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var carMgr []model.CarMgr
	/*
		SELECT
		mgrs.id as CarMgrId,
		cars.car_name as CarName,
		cars.car_type as CarType,
		cars.car_price as CarPrice,
		cars.car_num as CarNum,
		cars.car_time as CarTime,
		mgrs.mgr_time as MgrTime,
		mgrs.mgr_type as MgrType,
		mgrs.mgr_status as MgrStatus,
		mgrs.mgr_people as MgrPeople
		FROM
		mgrs
		LEFT JOIN cars ON cars.id = mgrs.cid
	*/
	redis_key := "car_mgr_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("mgrs").Select(
			"mgrs.id as CarMgrId",
			"cars.car_name as CarName",
			"cars.car_type as CarType",
			"cars.car_price as CarPrice",
			"cars.car_num as CarNum",
			"cars.car_time as CarTime",
			"mgrs.mgr_time as MgrTime",
			"mgrs.mgr_type as MgrType",
			"mgrs.mgr_status as MgrStatus",
			"mgrs.mgr_people as MgrPeople",
		).Joins("LEFT JOIN cars ON cars.id = mgrs.cid").
			Offset(offset).Limit(size).Find(&carMgr)
		jsonData, _ := json.Marshal(carMgr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carMgr)
	}
	var total int64
	model.DB.Model(&model.Mgr{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"data":  carMgr,
		"total": total,
	})
	return
}
func CarMgrDetail(c *gin.Context) {
	id := c.Query("id")
	var carMgr model.CarMgr
	/*
		SELECT
		mgrs.id as CarMgrId,
		cars.car_name as CarName,
		cars.car_type as CarType,
		cars.car_price as CarPrice,
		cars.car_num as CarNum,
		cars.car_time as CarTime,
		mgrs.mgr_time as MgrTime,
		mgrs.mgr_type as MgrType,
		mgrs.mgr_status as MgrStatus,
		mgrs.mgr_people as MgrPeople
		FROM
		mgrs
		LEFT JOIN cars ON cars.id = mgrs.cid
		WHERE mgrs.id=1
	*/
	redis_key := "car_mgr_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("mgrs").Select(
			"mgrs.id as CarMgrId",
			"cars.car_name as CarName",
			"cars.car_type as CarType",
			"cars.car_price as CarPrice",
			"cars.car_num as CarNum",
			"cars.car_time as CarTime",
			"mgrs.mgr_time as MgrTime",
			"mgrs.mgr_type as MgrType",
			"mgrs.mgr_status as MgrStatus",
			"mgrs.mgr_people as MgrPeople",
		).Joins("LEFT JOIN cars ON cars.id = mgrs.cid").
			Where("mgrs.id=?", id).Find(&carMgr)
		jsonData, _ := json.Marshal(carMgr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carMgr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": carMgr,
	})
	return
}
